import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, onBeforeUnmount } from "vue";
import {
  SuperviseModelDevelopStrategyList,
  SuperviseModelDevelopStrategySwitch,
  SuperviseModelDevelopAddOrUpdateStrategy
} from "@/api/stu/FinancialSupervision";
import { emitter } from "@/utils/mitt";
import qs from "qs";
export function useWashTacticsCenter(models) {
  const route = useRoute();
  const Refform = ref();
  const CreditVisible = ref(false)
  const loading = ref<boolean>(true);
  const btnloading = ref<boolean>(false);
  const dataList = ref([]);
  const updateTitle = ref('新增');
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const form = reactive({
    decision: [],
    riskLevel: "",
    strategyType: models,
    strategyName: "",
    studentAnswer: "",
    customerScreening: "",
    strategyCenterId: null //新增时为null
  })

  const rules = {
    strategyName: [
      {
        required: true,
        message: "请输入策略名称",
        trigger: "blur"
      }
    ],
    riskLevel: [
      {
        required: true,
        message: "请选择风险等级",
        trigger: "blur"
      }
    ],
    decision: [
      {
        required: true,
        message: "请选择策略决策",
        trigger: "blur"
      }
    ],
  }

  // 策略决策列表
  const DecisionList = [
    {
      id: "1",
      label: "登记客户信息",
    },
    {
      id: "2",
      label: "核查客户证件",
    },
    {
      id: "3",
      label: "留存客户身份证件复印件",
    },
    {
      id: "4",
      label: "要求客户补充其他身份资料或者身份证明文件",
    },
    {
      id: "5",
      label: "回访客户,实地查访",
    },
    {
      id: "6",
      label: "向公安,工商行政管理等部门核实",
    },
    {
      id: "7",
      label: "上报上级单位",
    },
    {
      id: "8",
      label: "上报当地人民银行",
    },
    {
      id: "9",
      label: "向当地公安机关报告",
    }
  ];
  const DecisionList2 = [
    {
      id: "1",
      label: "冻结账户",
    },
    {
      id: "2",
      label: "要求真实申请人提供书面的争议请求（虚假申请）",
    },
    {
      id: "3",
      label: "人工核实",
    },
    {
      id: "4",
      label: "挂起交易（暂时不允许成交）",
    },
    {
      id: "5",
      label: "记入黑名单",
    },
    {
      id: "6",
      label: "报告当地公安,司法部门",
    },
    {
      id: "7",
      label: "将涉嫌欺诈交易的卡账户列入止付名单（失窃卡）",
    },
    {
      id: "8",
      label: "上报中国银联欺诈交易报送系统",
    },
  ];

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "策略名称",
      prop: "strategyName",
    },
    {
      label: "风险等级",
      prop: "riskLevel",
    },
    {
      label: "决策",
      prop: "decision",
    },
    // {
    //   label: "修改时间",
    //   prop: "modificationTime",
    // },
    // {
    //   label: "状态",
    //   prop: "state",
    //   cellRenderer: ({ row }) => (
    //     <span>
    //       {
    //         row.state == 0 ? "已暂停" : "开启"
    //       }
    //     </span>
    //   )
    // },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "模型名称",
      prop: "strategyName",
    },
    {
      label: "风险等级",
      prop: "riskLevel",
    },
    // {
    //   label: "修改时间",
    //   prop: "modificationTime",
    // },
    // {
    //   label: "状态",
    //   prop: "state",
    //   cellRenderer: ({ row }) => (
    //     <span>
    //       {
    //         row.state == 0 ? "暂停" : "开启"
    //       }
    //     </span>
    //   )
    // },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function handleSizeChange() {
    GetDataList()
  }

  function handleCurrentChange() {
    GetDataList()
  }

  function CloseVisible(row: FormInstance) {
    emitter.emit("clearChooses")
    row.resetFields();
    CreditVisible.value = false;
    form.customerScreening = ""
  }

  // 暂停
  async function hanStop(row) {
    const data = {
      taskId: row.taskId,
      planId: row.planId,
      detailId: row.strategyCenterId,
      studentAnswer: row.studentAnswer
    }
    const res = await SuperviseModelDevelopStrategySwitch(data);
    if (res.success) {
      GetDataList();
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  }
  // 编辑
  function hanRedact(row) {
    CreditVisible.value = true;
    if (row) {
      updateTitle.value = '编辑';
      const filter = JSON.parse(row.filter)
      const filters = filter.map(el => {
        el.selectMore = el.selectMore == '' ? '' : el.selectMore.split(' | ')
        return el
      });
      console.log("123", filters)
      nextTick(() => {
        form.strategyName = row.strategyName;
        form.riskLevel = row.riskLevel;
        form.strategyCenterId = row.strategyCenterId;
        form.customerScreening = filters;
        form.decision = row.decision.split("|");
      })
    } else {
      updateTitle.value = '新增'
      form.strategyCenterId = null;
    }
  }

  // 提交新建 or 修改策略
  function stubim_form(row: FormInstance) {
    if (!row) return;
    (row as any).validate(async valid => {
      if (valid) {
        emitter.emit("setChoose"); // 调用子组件的方法
      }
    })
  }
  // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  // TOD 子组件传参给父组件
  emitter.on("StubimData", async arr => {
    const data = {
      ...form,
      planId: route.query.planId,
      taskId: route.query.taskId,
      customerScreening: arr,
      studentAnswer: JSON.stringify(form)
    };
    btnloading.value = true;
    const res = await SuperviseModelDevelopAddOrUpdateStrategy(data);
    if (res.success) {
      ElMessage.success(res.msg);
      GetDataList()
      CloseVisible(Refform.value)
      btnloading.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        btnloading.value = false;
      }, 1500)
    }
  })

  // 获取数据列表
  async function GetDataList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
      strategyType: models
    };
    const res = await SuperviseModelDevelopStrategyList(data);
    if (res.success) {
      dataList.value = res.data.items
      pagination.total = res.data.totalCount;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false }, 1500)
    }
  }

  onBeforeUnmount(() => {
    emitter.off("StubimData");
    emitter.off("setChoose")
  })

  onMounted(() => {
    GetDataList();
  })


  return {
    form,
    rules,
    Refform,
    loading,
    columns,
    columns2,
    dataList,
    btnloading,
    pagination,
    updateTitle,
    DecisionList,
    DecisionList2,
    CreditVisible,
    hanStop,
    hanRedact,
    stubim_form,
    CloseVisible,
    handleSizeChange,
    handleCurrentChange
  }
}
